﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NP.BPMReportPlatform.AD;
using NP.BPMReportPlatform.AD.Dto;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.ZHLC
{
    public class ADService : BPMReportPlatformAppService, IADService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;

        public ADService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        public async Task<PagedResultDto<GetBXLPDJOutput>> GetAllAsync(GetBXLPDJInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetBXLPDJOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetBXLPDJOutput>> ExportAsync(GetBXLPDJInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetBXLPDJOutput> GetQueryable(GetBXLPDJInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>().Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }
            var listQueryable = _db.Queryable<InsuranceClaimsHeader, BusinessProcessesNew>(
                    (x, b) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == b.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, x => x.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),x => x.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(), (x, b) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), b.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName), x => x.AddUserName.Contains(input.AddUserName))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AssetNo), x => x.AssetNo.Contains(input.AssetNo))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    x => x.AddTime >= input.StartCreationTime && x.AddTime <= input.EndCreationTime)
                .Select((x, b) => new GetBXLPDJOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    ProcessStartTime = x.AddTime,
                    ProcessStartUserName = x.AddUserName,
                    OrderStatus = b.ProcessStatusName,
                    IncidentDate =x.IncidentDate,
                    CaseDes = x.CaseDes,
                    AssetNo = x.AssetNo,
                    AssetName =x.AssetName,
                    CaseContent =  x.CaseContent,
                    DamagesAmount =x.DamagesAmount.Value,
                    WbbaCode =x.WbbaCode,
                    WbzsbaDate =x.WbzsbaDate,
                    XckcDate =x.XckcDate,
                    ZldjDate =x.ZldjDate,
                    ZlshDate =x.ZlshDate,
                    TjfaddDate =x.TjfaddDate,
                    TjfawcDate =x.TjfawcDate,
                    GzqrDate =x.GzqrDate,
                    LpdzDate =x.LpdzDate,
                    SkrzDate =x.SkrzDate,
                    Remark =x.Remark
                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            return listQueryable;
        }
    }
}